package org.example;

import org.example.entity.Report;
import org.example.model.CallParam;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.document.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;

import java.io.IOException;
import java.util.List;

/**
 * AI控制器类 - 提供AI聊天相关的REST API端点
 * 处理客户端的AI聊天请求并返回流式响应
 */
@RestController // 标记为REST控制器，自动将响应转换为JSON
@RequestMapping("/ai") // 设置基础请求路径
public class AIController {

    /**
     * AI服务实例 - 通过构造函数注入
     */
    private final AIService aiService;

    /**
     * 构造函数 - 自动注入AIService实例
     *
     * @param aiService AI服务实例，用于处理AI响应生成
     */
    public AIController(AIService aiService) {
        this.aiService = aiService;
    }

    @Autowired ReportResultService reportResultService;

    /**
     * 聊天API端点 - 提供流式AI聊天响应
     *
     * @param prompt         用户输入的提示文本
     * @param conversationId 对话会话ID，用于维护对话上下文
     * @return Flux<ChatResponse> - 反应式流，包含AI模型的流式响应
     */
    @GetMapping(value = "/chat", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<ChatResponse> chat(
            @RequestParam String prompt, // 用户输入参数
            @RequestParam String conversationId) { // 会话ID参数

        // 调用AI服务生成响应并返回流式结果
        return aiService.generateResponse(prompt, conversationId);
    }

    @PostMapping(value = "/genReport")
    public String genReport(@RequestBody CallParam callParam) throws IOException {
        return aiService.generateReportResponse(
                callParam.getPrompt());
    }

    @PostMapping(value = "/call")
    public String call(@RequestBody CallParam callParam) {
        return aiService.generateResponseBatch(callParam.getPrompt(), callParam.getConversationId());
    }

    @GetMapping("/report")
    public Report getMethodName(@RequestParam String filename) {
        String suffix = ".json";
        if (filename.endsWith(suffix)) {
            filename = filename.substring(0, filename.length() - suffix.length());
        }
        return reportResultService.readJsonFromDb(filename);
    }

    @GetMapping("/listReport")
    public List<Report> listReport() {
        return reportResultService.listReport();
    }

    @PostMapping("/addDoc")
    public String addDoc(@RequestBody String content) {
        aiService.addDocument(content);
        return "success";
    }

    @PostMapping("/searchDoc" )
    public List<String> searchDoc(@RequestBody String query) {
        return aiService.searchDocument(query).stream().map(Document::getText).toList();
    }
}
